﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Xls;
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;
using System.IO;
using Spire.Xls.Core;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Windows.Forms;
using Spire.Doc.Fields;
using Section = Spire.Doc.Section;
using TextRange = Spire.Presentation.TextRange;

namespace RMSWebService
{
    public class WaterMarkProvider
    {
        public static bool WaterMarkPPT(string strWaterMark,string filePath, string fileName, out string strError)
        {
            bool bresult = true;
            strError = string.Empty;
            Presentation ppt = new Presentation();
            Presentation presentation = new Presentation();
            try
            {
                bool flag = Path.GetExtension(fileName) == ".pptx";
                if (flag)
                {
                    presentation.LoadFromFile(filePath, Spire.Presentation.FileFormat.Pptx2013);
                }
                else
                {
                    presentation.LoadFromFile(filePath, Spire.Presentation.FileFormat.PPT);
                }
             //   RectangleF rect = new RectangleF(340f, 150f, 300f, 200f);
                foreach (object obj in presentation.Masters)
                {
                      Font font = new Font("宋体", 20);   
                  SizeF size = TextRenderer.MeasureText(strWaterMark, font);
                    IMasterSlide masterSlide = (IMasterSlide)obj;
                    float x = 30;
                    float y = 80;
                    for (int i = 0; i < 3; i++)
                    {
                        for (int j = 0; j < 3; j++)
                        {
                            //绘制文本，设置文本格式并将其添加到第一张幻灯片
                            RectangleF rect = new RectangleF(x, y, size.Width, size.Height);
                            IAutoShape shape = masterSlide.Shapes.AppendShape(Spire.Presentation.ShapeType.Rectangle, rect);
                            shape.TextFrame.Text = strWaterMark;
                            shape.Fill.FillType = FillFormatType.None;
                            shape.ShapeStyle.LineColor.Color = Color.White;
                            shape.Rotation = -45;
                            shape.Locking.SelectionProtection = true;
                            shape.Line.FillType = FillFormatType.None;
                            TextRange textRange = shape.TextFrame.TextRange;
                            textRange.Fill.FillType = FillFormatType.Solid;
                            textRange.Fill.SolidColor.Color = Color.FromArgb(120, Color.LightGray);
                            textRange.EastAsianFont = new TextFont(font.Name);
                            textRange.FontHeight = font.Size;

                            x += (200 + size.Width);
                        }
                        x = 30;
                        y += (200 + size.Height);
                    }
                 
                    //TextRange textRange = shape.TextFrame.TextRange;
                    //textRange.Fill.FillType = FillFormatType.Solid;
                    //textRange.Fill.SolidColor.Color = Color.FromArgb(120, Color.LightGray);
                    //textRange.FontHeight = 16f;
                    //shape.Fill.FillType = FillFormatType.None;
                    //shape.Rotation = -45f;
                    //shape.Locking.SelectionProtection = true;
                    //shape.Line.FillType = FillFormatType.None;
                }
                bool flag2 = Path.GetExtension(fileName) == ".pptx";
                if (flag2)
                {
                    presentation.SaveToFile(filePath, Spire.Presentation.FileFormat.Pptx2013);
                }
                else
                {
                    filePath += "x";
                    presentation.SaveToFile(filePath, Spire.Presentation.FileFormat.Pptx2013);
                }
            }
            catch (Exception ex)
            {
                bresult = false;
                strError = "添加水印失败：" + ex.Message;
            }
            presentation.Dispose();
            return bresult;
        }

        public static bool WaterMarkExcel(string strWaterMark, string filePath,string fileName, out string strError)
        {
            bool bresult = true;
            strError = string.Empty;
            Workbook workbook = new Workbook();
            try
            {
                bool flag = Path.GetExtension(fileName) == ".xlsx";
                //if (flag)
                //{
                //    workbook.LoadFromFile(@"C:\www\Wm\bin\1.xlsx", ExcelVersion.Version2013);
                //}
                //else
                //{
                //    workbook.LoadFromFile(@"C:\www\Wm\bin\1.xlsx", ExcelVersion.Version97to2003);
                //}
                if (flag)
                {
                    workbook.LoadFromFile(filePath, ExcelVersion.Version2013);
                }
                else
                {
                    workbook.LoadFromFile(filePath, ExcelVersion.Version97to2003);
                }
                Font font = new Font("宋体", 20f);
                foreach (IWorksheet worksheet in workbook.Worksheets)
                {
                    Worksheet sheet = (Worksheet)worksheet;
                    Image imgWtrmrk = WaterMarkProvider.DrawText(strWaterMark, font, Color.LightGray, Color.White, sheet.PageSetup.PageHeight, sheet.PageSetup.PageWidth);
                    sheet.PageSetup.BackgoundImage = (imgWtrmrk as Bitmap);
                }
                bool flag2 = Path.GetExtension(fileName) == ".xlsx";
                if (flag2)
                {
                    workbook.SaveToFile(filePath, ExcelVersion.Version2016);
                }
                else
                {
                    workbook.SaveToFile(filePath, ExcelVersion.Version97to2003);
                }
            }
            catch (Exception ex)
            {
                bresult = false;
                strError = "添加水印失败：" + ex.Message;
            }
            workbook.Dispose();
            return bresult;
        }

        internal static bool WaterMarkWord1(string strWatertMark, string tempPath, string svg, string fileName, out string strError)
        {
            string filePath = tempPath;
            bool bresult = true;
            strError = string.Empty;
            Document document = new Document();
            try
            {
                document.LoadFromFile(filePath);
                document.Watermark = new TextWatermark
                {
                    Text = strWatertMark,
                    FontSize = 20f,
                    Color = Color.LightGray,
                    Layout = WatermarkLayout.Horizontal,

                };
                bool flag = Path.GetExtension(fileName) == ".docx";
                if (flag)
                {
                    document.SaveToFile(filePath, Spire.Doc.FileFormat.Docx2010);
                    document.SaveToFile(svg, Spire.Doc.FileFormat.SVG);
                }
                else
                {
                    document.SaveToFile(filePath, Spire.Doc.FileFormat.Doc);
                    document.SaveToFile(svg, Spire.Doc.FileFormat.SVG);
                }

                document.Close();
            }
            catch (Exception ex)
            {
                bresult = false;
                strError = "添加水印失败：" + ex.Message;
            }
            document.Dispose();
            return bresult;
        }

        public static bool WaterMarkWord(string strWaterMark, string filePath,string fileName, out string strError)
        {
            bool bresult = true;
            strError = string.Empty;
            Document document = new Document();
            try
            {
                document.LoadFromFile(filePath);
                ShapeObject shape = new ShapeObject(document, Spire.Doc.Documents.ShapeType.TextPlainText);
                shape.Width = 150;
                shape.Height = 20;

                //设置艺术字文本内容、位置及样式
                shape.VerticalPosition = 60;
                shape.HorizontalPosition = 30;
                shape.Rotation = 325;
                shape.WordArt.Text = strWaterMark;

                shape.FillColor = System.Drawing.Color.Gray;
                shape.StrokeColor = System.Drawing.Color.Gray;

                Section section;
                HeaderFooter header;
                for (int n = 0; n < document.Sections.Count; n++)
                {
                    section = document.Sections[n];

                    //获取section的页眉
                    header = section.HeadersFooters.Header;
                    Paragraph paragraph1;
                    for (int i = 0; i < 3; i++)
                    {
                        //添加段落到页眉
                        paragraph1 = header.AddParagraph();
                        for (int j = 0; j < 4; j++)
                        {
                            //复制艺术字并设置多行多列位置
                            shape = (ShapeObject)shape.Clone();
                            shape.VerticalPosition = 50 + 250 * i;

                            shape.HorizontalPosition = 20 + 260 * j;
                            paragraph1.ChildObjects.Add(shape);

                        }
                    }
                }



                //document.Watermark = new TextWatermark
                //{
                //    Text = strWaterMark,
                //    FontSize = 20f,
                //    Color = Color.LightGray,
                //    Layout = WatermarkLayout.Horizontal,

                //};
                bool flag = Path.GetExtension(fileName) == ".docx";
                if (flag)
                {
                    document.SaveToFile(filePath, Spire.Doc.FileFormat.Docx2010);
                }
                else
                {
                    document.SaveToFile(filePath, Spire.Doc.FileFormat.Doc);
                }
                document.Close();
            }
            catch (Exception ex)
            {
                bresult = false;
                strError = "添加水印失败：" + ex.Message;
            }
            document.Dispose();
            return bresult;
        }
        public static bool WaterMarkPDF(string strWaterMark, string filePath, string fileName, out string strError)
        {
            bool bresult = true;
            strError = string.Empty;
            PdfDocument pdf = new PdfDocument();
            try
            {
                pdf.LoadFromFile(filePath);
                PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("宋体", 20f), true);
                SizeF fontSize = font.MeasureString(strWaterMark);
                float offset = (float)((double)fontSize.Width * Math.Sqrt(2.0) / 4.0);
                float offset2 = (float)((double)fontSize.Height * Math.Sqrt(2.0) / 4.0);
                foreach (object obj in pdf.Pages)
                {
                    PdfPageBase page = (PdfPageBase)obj;
                    PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.Size.Width / 2f, page.Canvas.Size.Height / 2f));
                    brush.Graphics.SetTransparency(0.8f);
                    brush.Graphics.TranslateTransform(brush.Size.Width / 2f - offset - offset2, brush.Size.Height / 2f + offset - offset2);
                    brush.Graphics.RotateTransform(-45f);
                    brush.Graphics.DrawString(strWaterMark, font, PdfBrushes.DarkGray, 0f, 0f);
                    page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0f, 0f), page.Canvas.Size));
                }
                pdf.SaveToFile(filePath);
                pdf.Close();
            }
            catch (Exception ex)
            {
                bresult = false;
                strError = "添加水印失败：" + ex.Message;
            }
            pdf.Dispose();
            return bresult;
        }
        private static Image DrawText(string text, Font font, Color textColor, Color backColor, double height, double width)
        {
            Image img = new Bitmap((int)width, (int)height);
            Graphics drawing = Graphics.FromImage(img);
            SizeF textSize = drawing.MeasureString(text, font);
            drawing.TranslateTransform(((float)((int)width) - textSize.Width) / 2f, ((float)((int)height) - textSize.Height) / 2f);
            drawing.RotateTransform(-45f);
            drawing.TranslateTransform(-((float)((int)width) - textSize.Width) / 2f, -((float)((int)height) - textSize.Height) / 2f);
            drawing.Clear(backColor);
            Brush textBrush = new SolidBrush(textColor);
            drawing.DrawString(text, font, textBrush, ((float)((int)width) - textSize.Width) / 2f, ((float)((int)height) - textSize.Height) / 2f);
            drawing.Save();
            return img;
        }
    }
}